#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <netinet/in.h>

#define MAXLINE 10
#define SERV_PORT 8888

int main(int argc, char *argv[]){
	struct sockaddr_in servaddr, clit_addr;
	socklen_t clitaddr_len;
	int listenfd, connfd;
	char buf[MAXLINE], str[INET_ADDRSTRLEN];
	int efd;

	listenfd = socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));

	listen(listenfd, 20);

	struct epoll_event event, resevent[MAXLINE];
	int res,len;

	efd = epoll_create(MAXLINE);
	event.events = EPOLLIN | EPOLLET; 	// 设置为边沿触发（ET模式）
	// event.events = EPOLLIN;			// 默认为水平触发（LT模式）
	
	printf("Accepting connecctions...");

	clitaddr_len = sizeof(clit_addr);
	connfd = accept(listenfd, (struct sockaddr*)&clit_addr, &clitaddr_len);

	printf("received from %s at PORT %d\n", inet_ntop(AF_INET, &clit_addr.sin_addr.s_addr, str, INET_ADDRSTRLEN), ntohs(clit_addr.sin_port));

	// 修改connfd为非阻塞读
	int flag;
	flag = fcntl(connfd, F_GETFL);
	flag |= O_NONBLOCK;
	fcntl(connfd, F_SETFL, flag);


	event.data.fd = connfd;
	epoll_ctl(efd, EPOLL_CTL_ADD, connfd, &event);

	while(1){
		res = epoll_wait(efd, resevent, MAXLINE, -1);
		printf("res %d\n", res);

		if(resevent[0].data.fd == connfd){
			len = read(connfd, buf, MAXLINE/2);
			write(STDOUT_FILENO, buf, len);
		}
	}

	return 0;
}

